package com.beemans.common.utils

import android.os.Build
import com.blankj.utilcode.util.*
import com.hjq.permissions.Permission
import com.tiamosu.fly.utils.createDir
import java.io.File
import java.util.*

/**
 * @author tiamosu
 * @date 2021/3/13
 *
 * 描述：设备唯一标识码工具类
 */
object CommonDeviceUtils {
    private const val DEVICE_FILE_DIR = "devices"
    private const val DEVICE_FILE_NAME = ".device"

    /**
     * 初始化设备唯一标识码
     */
    fun initDeviceId() {
        //从 mmkv 存储获取
        var deviceId = CommonCacheUtils.deviceId
        if (deviceId?.isNotBlank() == true) {
            val deviceIdBySd = getDeviceIdBySd()
            LogUtils.iTag("tiamosu", "deviceIdBySd:$deviceIdBySd")

            if (deviceIdBySd.isNullOrBlank()) {
                saveDeviceId(deviceId)
            } else if (deviceIdBySd != deviceId) {
                updateDeviceId(deviceIdBySd)
            }
            return
        }
        //从手机存储获取
        deviceId = getDeviceIdBySd()

        //创建设备唯一标识码
        if (deviceId.isNullOrBlank()) {
            deviceId = DeviceUtils.getUniqueDeviceId()
        }
        deviceId?.let {
            updateDeviceId(deviceId)
            saveDeviceId(deviceId)
        }
    }

    /**
     * 获取设备唯一标识码
     *
     * @param isCreateNew 是否创建新设备id，方便测试用
     */
    fun getDeviceId(isCreateNew: Boolean = false): String {
        val deviceId = CommonCacheUtils.deviceId
        if (deviceId?.isNotBlank() == true) {
            return deviceId
        }
        if (isCreateNew) {
            createNewDeviceId()
        } else {
            initDeviceId()
        }
        return CommonCacheUtils.deviceId ?: ""
    }

    /**
     * 创建新设备id
     */
    private fun createNewDeviceId() {
        val deviceId = UUID.randomUUID().toString().replace("-", "")
        CommonCacheUtils.deviceId = deviceId
    }

    /**
     * 更新设备唯一标识码
     */
    private fun updateDeviceId(deviceId: String) {
        CommonCacheUtils.deviceId = deviceId
    }

    private fun getDeviceIdBySd(): String? {
        val deviceFile = getDeviceFile() ?: return null
        return FileIOUtils.readFile2String(deviceFile)
    }

    private fun saveDeviceId(deviceId: String): Boolean {
        val deviceFile = getDeviceFile() ?: return false
        val isWriteSuc = FileIOUtils.writeFileFromString(deviceFile, deviceId)
        LogUtils.iTag("tiamosu", "设备标识码文件保存${(if (isWriteSuc) "成功" else "失败")}~")
        return isWriteSuc
    }

    private fun getDeviceFile(): File? {
        //Android Q 平台上直接从外部存储私有目录获取
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q
            || !PermissionHelper.isGranted(*Permission.Group.STORAGE)
        ) {
            return null
        }

        var parentPath = SDCardUtils.getSDCardPathByEnvironment()
        if (parentPath.isBlank()) {
            parentPath = Utils.getApp().getExternalFilesDir(null)?.absolutePath
        }
        val cropDir = createDir(File(parentPath, DEVICE_FILE_DIR))
        val deviceFile = File(cropDir, DEVICE_FILE_NAME)
        LogUtils.iTag("tiamosu", "z=============:" + deviceFile.absolutePath)
        return deviceFile
    }
}